package com.ruoyi.mobile.project.task;

import com.ruoyi.db.oms.domain.OmsOrder;
import com.ruoyi.db.oms.domain.OmsOrderGoods;
import com.ruoyi.mobile.task.Task;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ruoyi.mobile.system.SystemConfig;
import com.ruoyi.mobile.utils.BeanUtil;
import com.ruoyi.mobile.project.pms.service.WxPmsGoodsProductService;
import com.ruoyi.mobile.project.oms.service.WxOmsOrderGoodsService;
import com.ruoyi.mobile.project.oms.service.WxOmsOrderService;
import com.ruoyi.mobile.project.utils.OrderUtil;

import java.time.LocalDateTime;
import java.util.List;

public class OrderUnpaidTask extends Task
{
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);
    private Long orderId = -1L;

    public OrderUnpaidTask(Long orderId, long delayInMilliseconds)
    {
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Long orderId)
    {
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run()
    {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);

        WxOmsOrderService orderService = BeanUtil.getBean(WxOmsOrderService.class);
        WxOmsOrderGoodsService orderGoodsService = BeanUtil.getBean(WxOmsOrderGoodsService.class);
        WxPmsGoodsProductService productService = BeanUtil.getBean(WxPmsGoodsProductService.class);

        OmsOrder order = orderService.findById(this.orderId);
        if (order == null)
        {
            return;
        }
        if (!OrderUtil.isCreateStatus(order))
        {
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0)
        {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        Long orderId = order.getId();
        List<OmsOrderGoods> orderGoodsList = orderGoodsService.queryByOid(orderId);
        for (OmsOrderGoods orderGoods : orderGoodsList)
        {
            Long productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (productService.addStock(productId, number) == 0)
            {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }
        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}
